package com.cxs.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 存储jwt和校验jwt
 */
@Data
@Component
// 从配置文件中读取过期时间和密钥
@ConfigurationProperties(prefix = "cxs.jwt")
public class JwtUtil {

    /**
     * jwt的过期时间
     */
    private long expire;
    /**
     * 密钥，从配置文件读取
     */
    private String secret;
    /**
     *
     */
    private String header;

    /**
     * 生成jwt
     * @param username
     * @return
     */
    public String generateToken(String username) {
        Date now = new Date();
        Date expireData = new Date(now.getTime() + 1000 * 60 * 60 * 24 * expire);
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(username)
                .setIssuedAt(now)
                .setExpiration(expireData)   // 过期时间
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 解析jwt
     * @param jwt
     * @return
     */
    public Claims getClaimByToken(String jwt) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * jwt是否过期
     * @param claims
     * @return
     */
    public boolean isTokenExpired(Claims claims) {
        return claims.getExpiration().before(new Date());
    }

}
